﻿using LibraryManagementSystem.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Text.Json;
using Microsoft.AspNetCore.Authorization;

namespace LibraryManagementSystem.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    [Authorize]
    public class LibraryController : ControllerBase
    {
        private readonly LibraryContext _context;

        public LibraryController(LibraryContext context)
        {
            _context = context;
        }


        [HttpPost("add")]
        public async Task<ActionResult<Libraryitem>> AddLibraryItem([FromBody] LibraryItemDto itemDto)
        {
           
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            Libraryitem libraryItem;

            if (itemDto.Type == "Book")
            {
                libraryItem = new Book
                {
                    Title = itemDto.Title,
                    Author = itemDto.Author,
                    CategoryId = itemDto.CategoryId,
                    Price = itemDto.Price,
                    TotalCopies = itemDto.TotalCopies,
                    AvailableCopies = itemDto.AvailableCopies,
                    Isbn = itemDto.BootCode,
                    Publisher = itemDto.PublisherAndIssueNumber
                };
            }
            else if (itemDto.Type == "Magazine")
            {
                libraryItem = new Magazine
                {
                    Title = itemDto.Title,
                    Author = itemDto.Author,
                    CategoryId = itemDto.CategoryId,
                    Price = itemDto.Price,
                    TotalCopies = itemDto.TotalCopies,
                    AvailableCopies = itemDto.AvailableCopies,
                    Issn = itemDto.BootCode,
                    IssueNumber = int.Parse( itemDto.PublisherAndIssueNumber)
                };
            }
            else
            {
                return BadRequest("Invalid item type.");
            }

            _context.Libraryitems.Add(libraryItem);
            await _context.SaveChangesAsync();

            return CreatedAtAction(nameof(GetLibraryItemById), new { id = libraryItem.Id }, libraryItem);
        }


        // DELETE: api/library/delete/5
        [HttpDelete("delete/{id}")]
        public async Task<IActionResult> DeleteLibraryItem(int id)
        {
            var item = await _context.Libraryitems.FindAsync(id);
            if (item == null)
            {
                return NotFound();
            }

            _context.Libraryitems.Remove(item);
            await _context.SaveChangesAsync();
            return NoContent();
        }

        [HttpPut("update/{id}")]
        public async Task<IActionResult> UpdateLibraryItem(int id, [FromBody] LibraryItemDto itemDto)
        {
     
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            var libraryitem = await _context.Libraryitems.FirstOrDefaultAsync(b => b.Id == id);
            if (libraryitem == null)
            {
                return NotFound();
            }

            // 检查类型是否匹配
            if ((libraryitem is Book && itemDto.Type != "Book") ||
                (libraryitem is Magazine && itemDto.Type != "Magazine"))
            {
                return BadRequest("Cannot change item type");
            }

            // 更新共有属性
            libraryitem.Title = itemDto.Title;
            libraryitem.Author = itemDto.Author;
            libraryitem.CategoryId = itemDto.CategoryId;
            libraryitem.Price = itemDto.Price;
            libraryitem.TotalCopies = itemDto.TotalCopies;
            libraryitem.AvailableCopies = itemDto.AvailableCopies;

            // 更新类型特定属性
            if (itemDto.Type == "Book" && libraryitem is Book book)
            {
                book.Isbn = itemDto.BootCode;
                book.Publisher = itemDto.PublisherAndIssueNumber;
            }
            else if (itemDto.Type == "Magazine" && libraryitem is Magazine magazine)
            {
                magazine.Issn = itemDto.BootCode;
                if (int.TryParse(itemDto.PublisherAndIssueNumber, out int issueNumber))
                {
                    magazine.IssueNumber = issueNumber;
                }
                else
                {
                    return BadRequest("Invalid issue number");
                }
            }
            else
            {
                return BadRequest("Invalid item type");
            }

            await _context.SaveChangesAsync(); 
            return Ok(libraryitem); 
        }

        // GET: api/library/search
        [HttpGet("search")]
        public async Task<ActionResult<IEnumerable<Libraryitem>>> SearchLibraryItems(string? title, string? author, string? isbn)
        {
            var query = _context.Libraryitems.AsQueryable();

            if (!string.IsNullOrEmpty(title))
            {
                query = query.Where(item => item.Title.Contains(title));
            }

            if (!string.IsNullOrEmpty(author))
            {
                query = query.Where(item => item.Author.Contains(author));
            }

            if (!string.IsNullOrEmpty(isbn) && isbn.Length == 13)
            {
                query = query.OfType<Book>().Where(book => book.Isbn == isbn);
            }

            return await query.ToListAsync();
        }

        // GET: api/library/get/5
        [HttpGet("get/{id}")]
        public async Task<ActionResult<Libraryitem>> GetLibraryItemById(int id)
        {
            var item = await _context.Libraryitems.FindAsync(id);

            if (item == null)
            {
                return NotFound();
            }

            return item;
        }
    }
}
